package cn.gjxblog.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.util.DigestUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2018/12/24 15:59
 */
public class QiniuUtil {
    private static final String accessKey = "belqPYDzrbRLPt8NXUod8ltUU3sdl4WYlsf49iV_";
    private static final String secretKey = "sMUEwryiDH-hSBV8cZxM1qBY-f0HVtF-8aykGEbF";
    private static final String bucket = "bishe";


    public static String upLoadImage(byte[] data, String fileName) {
        //图片的外链地址
        StringBuffer imgUrl = new StringBuffer("http://img.gjxblog.cn/");
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);

        //...生成上传凭证，然后准备上传
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = simpleDateFormat.format(new Date());
        String relativePath = format + "/" + DigestUtils.md5DigestAsHex(fileName.getBytes());

        try {
            Response response = uploadManager.put(data, relativePath, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            imgUrl.append(putRet.key);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return imgUrl.toString();
    }

}
